from typing import Dict, List
import asyncio
from langgraph.graph import StateGraph, END
from .factor_engine import FactorEngine, TechnicalFactor, CrossSectionalFactor
from ..storage.factor_storage import FactorStorage
from ..calculation.technical import TechnicalIndicator
from ..service.factor_service_impl import FactorServiceImpl
from datetime import datetime
from src.data_agent.core.data_agent import DataAgent
from typing import Optional, Dict, List
import asyncio

class MissingDependencyError(Exception):
    """因子依赖缺失异常"""
    pass

class RiskViolationError(Exception):
    """风控规则违反异常"""
    pass

class FactorAgent:
    """因子智能体核心类"""
    
    def __init__(self):
        self.engine = FactorEngine()
        self.storage = FactorStorage()
        self.service = FactorServiceImpl(self)
        self._init_workflow()
        
    def _init_workflow(self):
        """初始化langgraph工作流"""
        self.workflow = StateGraph(dict)
        self.workflow.add_node("validate", self._validate_input)
        self.workflow.add_node("compute", self._compute_factor)
        self.workflow.add_node("store", self._store_result)
        
        self.workflow.set_entry_point("validate")
        self.workflow.add_edge("validate", "compute")
        self.workflow.add_edge("compute", "store")
        self.workflow.add_edge("store", END)
        
    async def process_request(self, request: Dict):
        """处理因子计算请求"""
        return await self.workflow.arun(request)
    
    async def _validate_input(self, state: Dict):
        """输入验证"""
        required = ['factor_name', 'symbol', 'start', 'end']
        if not all(k in state for k in required):
            raise ValueError(f"缺少必要参数: {required}")
        return state
    
    async def _compute_factor(self, state: Dict):
        """执行因子计算"""
        data = await self._get_source_data(state)
        state['result'] = self.engine.compute_batch(
            data, [state['factor_name']]
        )
        return state
    
    async def _store_result(self, state: Dict):
        """存储计算结果"""
        self.storage.save(
            state['factor_name'],
            state['result'],
            {'start': state['start'], 'end': state['end']}
        )
        return state
    
    async def _get_source_data(self, state: Dict):
        """从数据智能体获取源数据"""
        # 假设已实现跨智能体通信
        return await DataAgent().fetch_data(
            state['symbol'],
            state['start'],
            state['end']
        )
    
    def auto_register_factors(self, configs: List[Dict]):
        """自动注册因子配置"""
        for config in configs:
            if config['type'] == 'technical':
                factor = TechnicalFactor(config)
            elif config['type'] == 'cross_section':
                factor = CrossSectionalFactor(config)
            self.engine.register_factor(factor)

    async def monitor_quality(self):
        """持续监控因子质量"""
        while True:
            await asyncio.sleep(3600)  # 每小时检查
            for factor in self.engine.factors.values():
                data = self.storage.load(factor.name)
                if self._check_anomaly(data):
                    self.service.trigger_alert(factor.name)
                    
    def _check_anomaly(self, data) -> bool:
        """检查数据异常"""
        return (data.isnull().mean() > 0.05).any()